app.controller('organizationuserctrl',function($scope, $state, $q, $timeout, organizationuserservice,importfileservice) {
	//列表头操作
	$scope.theadControl = {};
	//列表尾部操作
	$scope.tfooter = {
			"tableState":false,
			"tfootControl":{}
	};
	//机构初始化
	$scope.dataForTheTree = [];
	$scope.isAuthData=false;
	$scope.initOrganizations=function(){
		organizationuserservice.initOrganizationTree().success(function(data){
			$scope.dataForTheTree=data.data;
			$scope.treeModel.data = data.data[0].children;
			$scope.treeModel.title = data.data[0].title;
			$scope.treeModel.expandedNodes = [data.data[0]];
		});
		organizationuserservice.findIsAuthData().success(function(data){
			$scope.isAuthData=data.data;
		});
	}
	$scope.searchCriteria="queryName";
	$scope.treeModel = {
		"option" : {
			nodeChildren: "children",
		    dirSelectable: true,
		    injectClasses: {
		    	ul: "tt-ul",
		        li: "item",
		        liSelected: "a7",
		        iExpanded: "glyphicon glyphicon-minus",
		        iCollapsed: "glyphicon glyphicon-plus",
		        iLeaf: "glyphicon glyphicon-leaf",
		        label: "a6",
		        labelSelected: "a8"
		    }
		}
	};
	//弹框机构初始化
	$scope.dataForShowTheTree = [];
	$scope.initShowOrganizations=function(){
		organizationuserservice.initOrganizationTree().success(function(data){
			$scope.dataForShowTheTree=data.data;
			$scope.treeShowModel.data = data.data[0].children;
			$scope.treeShowModel.title = data.data[0].title;
			$scope.treeShowModel.expandedNodes = [data.data[0]];
		});
	}
    $scope.treeShowModel = {
		"option" : {
			nodeChildren: "children",
		    dirSelectable: true,
		    injectClasses: {
		    	ul: "tt-ul",
		        li: "item",
		        liSelected: "a7",
		        iExpanded: "glyphicon glyphicon-minus",
		        iCollapsed: "glyphicon glyphicon-plus",
		        iLeaf: "glyphicon glyphicon-leaf",
		        label: "a6",
		        labelSelected: "a8"
		    }
		}
	};
	
	//单击节点事件
	$scope.orgBean={"organizationId":""};
	$scope.showSelected=function(node){
		$scope.datagrid.selectionAll = false;
		$scope.orgBean=node;
		$scope.refreshsystem();
	}
	
	//刷新列表
	$scope.refreshsystem = function() {
		$scope.tableControl.reload();
	}
	
	//刷新列表
	$scope.org={"queryChilderOrg":false};
	
	//新列表分页查询 开始 ----------------------------------------
	$scope.tableControl = {
		init : {
			'queryFun':function(params, paramsObj){
				return $scope.getResource(params, paramsObj);
			}
		},
		callbackFun:function(){
			$scope.reloadDataGrid();
			$timeout(function(){
				$scope.tfooter.tfootControl.reCalculateScroll();
				$scope.theadControl.theadInit();
			});
			
		}
	};
	//新列表分页查询 结束 ----------------------------------------
	$scope.getResource = function(params, paramsObj) {
		$scope.datagrid.selectionAll=false;
		$scope.datagrid.selectionIds=[];
		if($scope.orgBean&&$scope.orgBean.organizationId){
			params+="&queryOrganizationId="+$scope.orgBean.organizationId;
		}
		//是否查询子节点用户
		var queryChilderOrg=$scope.org.queryChilderOrg;
		params+="&queryChilderOrg="+queryChilderOrg;
		if($scope.searchCriteria&&$scope.searchForm && "" !== $scope.searchForm){
			params+="&"+$scope.searchCriteria+"="+$scope.searchForm
		}
		return organizationuserservice.findList(params, paramsObj);
	}
	
	//获取职级
	organizationuserservice.findProlevelList().success(function(data){
		$scope.prolevelList=data.data;
	});
	
	//获取职位
	organizationuserservice.findPostList().success(function(data){
		$scope.postList=data.data.resultList;
	});
	
	//处理用户扩展字段
	$scope.getUserField=function(list){
		var newList=[];
		var twoList=[];
		for(var a in list){
			twoList.push(list[a]);
			if(twoList.length==2){
				newList.push(twoList);
				twoList=[];
			}
		}
		if(twoList.length>0){
			newList.push(twoList);
		}
		return newList;
	}
	
	//新增机构用户
	$scope.baseUserInfo={};
	$scope.isEdit=true;
	$scope.preAdd=function(organizationBean){
		organizationuserservice.preAdd().success(function(data){
			$scope.userFieldList=$scope.getUserField(data.data.userExtList);
			$scope.baseUserInfo={};
			$scope.isEdit=false;
			$scope.canEdit = true;
			$scope.baseUserInfo.organizationId=organizationBean.organizationId;
			$scope.baseUserInfo.gender=1;
			$scope.baseUserInfo.organizationName=organizationBean.organizationName;
			$("#formModel").modal("show");
		});
	}
	
	//新增或修改人员
	$scope.addOrUpdateOrgUser=function(){
		//转换数据
		var list=$scope.userFieldList;
		var coverList=[];
		for(var a in list){
			for(var b in list[a]){
				if(!isNaN(b)){
					var userField={"colCode":list[a][b].colCode,"colDisName":list[a][b].colDisName,"colValue":list[a][b].colValue};
					coverList.push(userField);
				}
			}
		}
		$scope.baseUserInfo.userExtList=coverList;
		//if(new ValidationService().checkFormValidity($scope.validateFormUser)) {
			if($scope.isEdit){
				organizationuserservice.updateOrgUser($scope.baseUserInfo).success(function(data){
					$("#formModel").modal("hide");
					$scope.refreshsystem();
				});
			}else{
				organizationuserservice.addOrgUser($scope.baseUserInfo).success(function(data){
					$("#formModel").modal("hide");
					$scope.refreshsystem();
				});
			}
		//}
		
	}
	
	//编辑
	$scope.canEdit = true;
	$scope.findOrgUser=function(orgUserId, canEdit){
		organizationuserservice.findOrgUser(orgUserId).success(function(data){
			$scope.baseUserInfo={};
			$scope.baseUserInfo=data.data;
			$scope.canEdit = canEdit;
			$scope.isEdit=true;
			$scope.userFieldList=$scope.getUserField($scope.baseUserInfo.userExtList);
			$("#formModel").modal("show");
		});
	}
	//单个用户状态修改
	$scope.updateSingleUserState = function(row, currentState, deferred){
		organizationuserservice.updateUserState(row.userId,currentState).success(function(){
			row.userState = currentState;
			$scope.refreshsystem();
			deferred.resolve();
		});
	}
	
	//调整用户状态
	$scope.updateUserState=function(userId,currentState){
		$scope.userIds={};
		if(userId){
			$scope.userIds=userId.join(",");
		}
		if($scope.userIds.length > 0){
			organizationuserservice.updateUserState($scope.userIds,currentState).success(function(){
				$scope.refreshsystem();
			});
		}
		
	}
	
	//设置为管理员，不带分级权限
	$scope.adminSetting=function(userId){
		organizationuserservice.adminSetting(userId).success(function(){
			$scope.refreshsystem();
		});
	}
	
	
	//设置为管理员，带分级权限
	$scope.setAdminManage=function(adminId){
		$scope.adminId=adminId;
		organizationuserservice.getAdminOrgScopeList(adminId).success(function(data){
			$scope.adminOrgScopeList=data.data.adminOrgScopeList;
			$scope.orgAuthList=data.data.orgAuthList;
			$("#authDataFormModel").modal("show");
		});
	}
	
	//新增行
	$scope.addOrgScope=function(){
		$scope.adminOrgScopeList.push({"orgAdminScopeId":"","organizationId":"","adminId":$scope.adminId,"dataCode":"","dataName":""});
	}
	
	//删除记录
	$scope.deleteByIndex=function(index){
		$scope.adminOrgScopeList.splice(index,1);
	}
	
	//保存分级权限数据
	$scope.saveOrgData=function(){
		var orgScopeList=$scope.adminOrgScopeList;
		var scopeList=[];
		for(var a in orgScopeList){
			for(var b in orgScopeList[a].dataCodeList){
				scopeList.push({"orgAdminScopeId":"","organizationId":orgScopeList[a].organizationBean.organizationId,"adminId":orgScopeList[a].adminId,"dataCode":orgScopeList[a].dataCodeList[b],"dataName":""});
			}
		}
		organizationuserservice.addAdminOrgScope(JSON.stringify(scopeList),$scope.adminId).success(function(data){
			$("#authDataFormModel").modal("hide");
			$scope.refreshsystem();
		});
	}
	
	//调动人员
	$scope.moveUser=function(ids){
		if(ids==""){
			$scope.msgInfo = "请选择调动人员信息";
			$("#messageModel").modal("show");
		}else{
			$scope.userIds={};
			if(ids){
				$scope.userIds=ids.join(",");
			}else{
				return;
			}
			$scope.moveOrg={};
			$("#moveUserFormModel").modal("show");
		}
		
	}
	
	//保存人员调动
	$scope.saveMoveOrgUser=function(organizationId){
		organizationuserservice.moveOrgUser($scope.userIds,organizationId).success(function(){
			$("#moveUserFormModel").modal("hide");
			$scope.refreshsystem();
			$scope.datagrid.selectionIds=[]
		});
	}
	
	$scope.selectTreeModel = {
		"option" : {
			nodeChildren: "children",
		    dirSelectable: true,
		    injectClasses: {
		        iExpanded: "glyphicon glyphicon-minus",
		        iCollapsed: "glyphicon glyphicon-plus",
		        iLeaf: "glyphicon glyphicon-leaf"
		    }
		}
	 };
	
	$scope.tableOpts = {
	    "cols" : [{
		      "operate" : "edit",
		      "isHidden" : function(row){
		        	return !$scope.isShowFunction('orguserlist-manage') || $scope.orgBean.organizationId=='organization_public';
		      },
		      "event" : function(row) {
		    	  $scope.findOrgUser(row.orgUserId, true);
		      }
	      },
	      {
		      "operate" : "organizationuser.manager",
		      "operateText":"重置密码",
		      "operateIcon":"glyphicon glyphicon-user",
		      "warningMsg":"确定要重置该用户密码吗？",
		      "warning":true,
		      "isHidden" : function(row){
		        	return !$scope.isShowFunction('orguserlist-manage') || $scope.orgBean.organizationId=='organization_public';
		      },
		      "event" : function(row) {
		    	  $scope.resetPassword(row.accountId);
		      }
		  },
		  {
		      "operate" : "organizationuser.manager",
		      "operateText":"设置为管理员",
		      "operateIcon":"glyphicon glyphicon-user",
		      "warningMsg":"确定设置为管理员吗？",
		      "warning":true,
		      "isHidden" : function(row){
		        	return row.adminUserId  || $scope.orgBean.organizationId=='organization_public';
		       },
		      "event" : function(row) {
		    	  if(!row.adminUserId&&$scope.isAuthData){
		    		  $scope.setAdminManage(row.userId);
		    	  }
		    	  if(!row.adminUserId&&!$scope.isAuthData){
		    		  $scope.adminSetting(row.userId);
		    	  }
		    	  
		      }
		  },{
		        "operate" : "enable",
				"warningMsg":"确定启用该用户吗？",
				"warning":true,
		        "isHidden" :function(row){
		        	
		        	return !$scope.isShowFunction('orguserlist-manage') || row.userState==1 || $scope.orgBean.organizationId=='organization_public';
		        },
		        "event" : function(row) {
		        	var deferred = $q.defer();
		        	$scope.updateSingleUserState(row, 1, deferred);
		        	return deferred.promise;
		        }
		   },{
		        "operate" : "disable",
				"warningMsg":"确定停用该用户吗？",
				"warning":true,
		        "isHidden" :function(row){
		        	
		        	return !$scope.isShowFunction('orguserlist-manage') || row.userState==2 || $scope.orgBean.organizationId=='organization_public';
		        },
		        "event" : function(row) {
		        	var deferred = $q.defer();
		        	$scope.updateSingleUserState(row, 2, deferred);
		        	return deferred.promise;
		        }
		   },{
			   "operate" : "orguser.moveuser",
			   "operateText":"调动人员",
			   "operateIcon":"glyphicon glyphicon-share-alt",
			   "event":function(row){
				   var userIdArr = [];
				   userIdArr.push(row.userId);
				   $scope.moveUser(userIdArr);
			   }
		   },{
			      "operate" : "lock",
			      "operateText":"锁定",
			      "operateIcon":"glyphicon glyphicon-lock",
			      "isHidden" : function(row){
			        	return !($scope.isShowFunction('orguserlist-manage')&&row.accountState==1);
			        },
			      "warningMsg":"确定锁定该账号吗？",
			      "warning":true,
			      "event" : function(row) {
			    	  $scope.updateAccountState(row.accountId,row.accountState);
			      }
			  },{
			      "operate" : "account.nolock",
			      "operateText":"解锁",
			      "operateIcon":"glyphicon glyphicon-lock",
			      "isHidden" : function(row){
			        	return !($scope.isShowFunction('orguserlist-manage')&&row.accountState==3);
			        },
			      "warningMsg":"确定解锁该账号吗？",
			      "warning":true,
			      "event" : function(row) {
			    	  $scope.updateAccountState(row.accountId,row.accountState);
			      }
			  }]
	  };
	
	//更新账户状态
	$scope.updateAccountState = function(accountId,currentState){
		var toState = 3;
		if(toState == currentState){
			toState = 1;
		}
		var account = {"accountId":accountId,"accountState":toState};
		organizationuserservice.update(account).success(function(data){
			$scope.refreshsystem();
		});
		
	}
	
	// 绑定账户状态
	$scope.bindAccountState = function(state) {
		var text = "";
		switch (state) {
		case 1:
			text = "/已激活";
			break;
		case 2:
			text = "/未激活";
			break;
		case 3:
			text = "/已锁定";
			break;
		case 4:
			text = "/已作废";
			break;
		}
		return text;
	}
	$scope.bindAccountStateCls = function(state) {
		var cls = "";
		switch (state) {
		case 1:
			cls = "text-success";
			break;
		case 2:
			cls = "text-info";
			break;
		case 3:
			cls = "text-warning";
			break;
		case 4:
			cls = "text-danger";
			break;
		}
		return cls;
	}
	
	// 绑定用户状态
	$scope.bindUserState = function(state) {
		var text = "";
		switch (state) {
		case 1:
			text = "启用";
			break;
		case 2:
			text = "停用";
			break;
		}
		return text;
	}
	$scope.bindUserStateCls = function(state) {
		var cls = "";
		switch (state) {
		case 1:
			cls = "text-success";
			break;
		case 2:
			cls = "text-info";
			break;
		}
		return cls;
	}
	
	
	//导入弹窗
	$scope.openImportModel = function(){
		var items = new Object();
		items.orgCode = "organizationUserInfo";
		items.beginRow = 3;
		items.needExtractor = false;
		items.callbackFunction = $scope.refreshsystem;
		importfileservice.openExcelExportModal(items).result.then(function(data){
			
		});
	}
	
	//管理员重置密码
	$scope.resetPassword=function(accountId){
		organizationuserservice.resetPassword(accountId).success(function(data){
			$scope.isShow=false;
			$scope.userbean=data.data.userBean;
			$scope.password=data.data.password;
			var mobile="";
			if($scope.userbean.mobilePhone&&$scope.userbean.mobilePhone!=""){
				isShow=true;
				var mobile = $scope.userbean.mobilePhone.replace(/(\d{3})(\d{4})/,function(match,$1,$2){
					return $1 + '****';
				});
			}
	        $scope.showMobile=mobile;
			$("#managerModal").modal("show");
		});
	}
	
	//导入结果查看
	$scope.openImportDetailModel = function(){
		var jsonData={"initStatecode":"organizationuser",
				"orgCode":"organizationUserInfo",
				"parMenuName":$state.current.data.menuName,
				"listPageSize":1
				};
		var storage = window.localStorage;
		storage.setItem("jsonData",JSON.stringify(jsonData));
		$state.go($scope.initStateCode('importresult'));
	}
	
	$scope.updateGroupManager = function(state, userId){
		$scope.userIds={};
		if(userId){
			$scope.userIds=userId.join(",");
		}
		if($scope.userIds.length > 0){
			organizationuserservice.updateGroupManager($scope.userIds,state).success(function(){
				$scope.refreshsystem();
			});
		}
	}
	
});